python4oceanographers

Learn python with examples applied to marine sciences.

Teaching a new class this semester

Starting next week I'll be teaching a new class (Introduction to Dynamical Oceanography). I'll be using the Introduction to Geophysical Fluid Dynamics, 2nd Edition book by Cushman-Roisin & Beckers. This book has an interesting approach where all the topics are shown from an analytical and numerical point of view.

However, there is one big issue with the numerical exercises, all the numerical experiments examples are MatlabTM code.

Well, since I have to read and learn this examples in order to prepare my lectures, so why not convert them to python while I do it?

Here is the first program from chapter 1. The aliasing animation demo.

In [2]:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from JSAnimation import IPython_display

def aliasanim(n=300, nper=2):
    """Time steps to reach nend/n revolutions with rate Omega
    nper: number of periods shown for the real signal
    n: number of initial sampling points per period."""

    twopi = 2 * np.pi

    k = np.arange(0, nper * n)
    t = twopi / (nper * n) * k * nper
    z = np.cos(t)

    fig = plt.figure()
    ax = plt.axes(xlim=(0, twopi*nper), ylim=(-1, 1))

    # Non-animated.
    ax.plot(t, z, 'k-')

    # Animated.
    line, = ax.plot([], [], 'b-o')
    text = ax.text(twopi*nper/2, 1.05, '')
    line.set_data([], [])

    def init():
        return line, text

    def animate(i):
        j = n-i+1
        ts, zs = [], []
        di = twopi / (nper*n) * nper * i * 4

        k = np.arange(0, j)
        ts = di * k
        zs = np.cos(ts)

        text.set_text('%2.2f' % (di/np.pi))
        line.set_data(ts, zs)
        return line, text

    return animation.FuncAnimation(fig, animate, init_func=init,
                                   frames=n, interval=250)

aliasanim(n=300, nper=2)
Out[2]:


Once Loop Reflect

The script is very similar to the orignal with the exception for the JS-animation. Hope that is useful for others. Soon I'll post more scripts from the book.

In [3]:
HTML(html)
Out[3]:

This post was written as an IPython notebook. It is available for download or as a static html.

Creative Commons License
python4oceanographers by Filipe Fernandes is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Based on a work at http://ocefpaf.github.io/.

Comments